package com.qiangesoft.wechat.core.handler.event;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qiangesoft.wechat.core.builder.TextOutMessageBuilder;
import com.qiangesoft.wechat.entity.WxUser;
import com.qiangesoft.wechat.service.IWxUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 微信公众号用户取消关注处理器
 *
 * @author qiangesoft
 * @date 2023-09-07
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UnsubscribeHandler implements WxMpMessageHandler {

    private final IWxUserService wxUserService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        if (!wxMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT) && !wxMessage.getEvent().equals(WxConsts.EventType.UNSUBSCRIBE)) {
            return null;
        }

        String openId = wxMessage.getFromUser();

        // 取消关注
        LambdaUpdateWrapper<WxUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(WxUser::getOpenId, openId)
                .set(WxUser::getAttentionFlag, false);
        wxUserService.update(updateWrapper);

        String outContent = "已取消关注xxx，再见！";
        return new TextOutMessageBuilder().build(outContent, wxMessage, wxMpService);
    }
}
